# -*- coding:utf-8 -*-

from django.db import models
from metlib.misc.misc import gen_uuid8
from metlib.shell.fileutil import *
from weblib.django_kits import *
# Create your models here.

# Depot是存储仓库的抽象(如一块硬盘, 一个文件夹等)
class Depot(models.Model):
    class Meta:
        pass

    name = models.CharField(max_length=64, unique=True, default=gen_uuid8, primary_key=True)
    path = models.CharField(max_length=255, blank=True, default='')
    fstype = models.CharField(max_length=32, default='local',
                                 choices=[
                                     ('local', 'local'),
                                     ('nfs', 'nfs'),
                                     ('s3', 's3'),
                                     ('s3c', 's3c')
                                 ])

    # 如果为真, 则仅在别的仓库都不能用时才使用这个仓库. 这样, 便可平衡地使用其他仓库, 又能留出足够的大空间供特殊情况用.
    reserved = models.BooleanField(default=False)

    max_size = models.BigIntegerField(default=1024*1024)
    free_size = models.BigIntegerField(default=1024*1024)

    create_dt = models.DateTimeField(default=local_now)
    access_dt = models.DateTimeField(default=local_now)
    modify_dt = models.DateTimeField(default=local_now)

    @property
    def used_size(self):
        return self.max_size - self.free_size
    @used_size.setter
    def used_size(self, value):
        self.free_size = self.max_size - value

    def clean(self):
        # 当从表单中更改max_size数值时, 自动刷新free_size
        self.update_used_size()
        self.modify_dt = local_now()

    @property
    def used_size_in_M(self):
        return '%.1f' % (self.used_size / float(1024 * 1024))

    @property
    def used_size_in_G(self):
        return '%.2f' % (self.used_size / float(1024*1024*1024))

    @property
    def max_size_in_M(self):
        return '%.1f' % (self.max_size / float(1024 * 1024))

    @property
    def max_size_in_G(self):
        return '%.2f' % (self.max_size / float(1024*1024*1024))

    def get_used_size(self):
        if self.fstype in ('local', 'nfs'):
            self.used_size = DU(self.path)
            self.modify_dt = local_now()
        return self.used_size

    def update_used_size(self, delta=None):
        if delta is None:
            self.get_used_size()
        else:
            self.free_size -= delta
        self.save()
        return self.used_size

    @property
    def is_critical(self):
        return self.used_size / float(self.max_size) >= 0.9

    @property
    def usage_ratio(self):
        return self.used_size / float(self.max_size)

    @property
    def usage_level(self):
        usage_ratio = self.used_size / float(self.max_size)
        if usage_ratio < 0.5:
            return "free"
        elif usage_ratio < 0.75:
            return "over_half"
        elif usage_ratio < 0.9:
            return "almost_full"
        else:
            return "critical"

    def __unicode__(self):
        return self.name

